package mainService.services;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import mainService.HTTPService;
import mainService.ServiceParams;
import mainService.data.IpClient;
import mainService.data.UsersConnected;
import databaseManager.connection.ConnectionManager;
import databaseManager.connection.IConnection;

/**
 * Servizio che permette di cancellare un utente del progetto.
 * Funzione del Pm.
 *  
 *  @author Nicola Davanzo
 *
 */

public class EliminaUtenteService extends WriterServices implements HTTPService {
	@Override
	public ArrayList<String> getServiceResult(ServiceParams params) {

		String username = params.getValue("username");
		if(!UsersConnected.getUsersConnected().getUtente(IpClient.getSingleton().getIp()).getRuolo().equalsIgnoreCase("Project Manager")){
			params.addParam("file", "noPermessi.html");
			return (new HttpFileServer()).getServiceResult(params);
		}
		
		// Verifico che non stai eliminando il PM
		IConnection manager = new ConnectionManager();
		manager.connect();
		Connection conn = manager.getConnection();
		Statement stmt;
		try {
			stmt = conn.createStatement();
			String qry="SELECT role FROM users WHERE username='"+username+"';";
			ResultSet rs = stmt.executeQuery(qry);
			rs.next();
			
			if(rs.getString("role").equalsIgnoreCase("Project Manager")){ // stai eliminando il pm!
				params.addParam("file", "cancellazionePM.html");
			}else{ // stai eliminando un utente generico. Puoi procedere
				
				String cmd = "DELETE FROM users where username= '" + username + "'";
				boolean var = updateDb(cmd);
				if (!var) {// inserimento non corretto
					params.addParam("file", "cancellazioneUtenteFallita.html");
				} else {
					params.addParam("file", "cancellazioneUtenteRiuscita.html");
				}
			}
		} catch (SQLException e) {
			params.addParam("file", "cancellazioneUtenteFallita.html");
			e.printStackTrace();
		}


		return (new HttpFileServer()).getServiceResult(params);
	}
}
